from tornado.web import authenticated
from common.BaseHandler import BaseHandler
from common.Models import Category, PostCateMiddle


class CategoryHandler(BaseHandler):
    @authenticated
    def get(self):
        if "api" in self.request.uri:
            result = self.result()
            data = self.get_params()
            page = int(data.get("page", 1))
            limit = int(data.get("limit", 5))
            try:
                categories = self.session.query(Category).filter_by(author_id=self.current_user, is_delete=0)
                data_count = categories.count()
                categories = categories.order_by(Category.create_time.desc()).limit(limit).offset((page-1)*limit).all()
                data_list = []
                for cate in categories:
                    data_list.append({
                        "id": cate.id,
                        "name": cate.name,
                        "post_count": self.session.query(PostCateMiddle).filter_by(category_id=cate.id).count(),
                        "create_time": str(cate.create_time)
                    })

                result["status"] = 1
                result["msg"] = "获取数据成功"
                result["data"] = {
                    "data_count": data_count,
                    "data_list": data_list
                }
            except Exception as e:
                self.logger.error(e)
            self.write(result)
        else:
            self.render("management/category.html")

    @authenticated
    def post(self):
        result = self.result()
        data = self.get_body()
        try:
            name = self.data_null(data, "category_name", "请输入名称！")
            obj_exist = self.session.query(Category).filter_by(name=name, author_id=self.current_user, is_delete=0).count()
            if obj_exist > 0:
                self.data_except("当前分类已存在！")
            category = Category(name=name, author_id=self.current_user)
            self.session.add(category)
            self.session.commit()
            result["status"] = 1
            result["msg"] = "新增分类成功"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="新增分类失败！")
        self.write(result)

    @authenticated
    def put(self):
        result = self.result()
        data = self.get_body()
        try:
            category_id = self.data_null(data, "category_id", "请选择要更改的分类！")
            name = self.data_null(data, "category_name", "请输入名称！")
            category_obj = self.session.query(Category).filter_by(id=category_id, author_id=self.current_user, is_delete=0).first()
            if not category_obj:
                self.data_except("当前选择的分类不存在！")
            name_exist = self.session.query(Category).filter_by(name=name, author_id=self.current_user, is_delete=0).count()
            if name_exist > 0:
                self.data_except("当前分类名称已存在！")
            category_obj.name = name
            self.session.commit()
            result["status"] = 1
            result["msg"] = "更改分类名称成功"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="更改分类名称失败！")
        self.write(result)

    @authenticated
    def delete(self):
        result = self.result()
        data = self.get_body()
        try:
            category_id = self.data_null(data, "category_id", "请选择要删除的分类！")
            category_obj = self.session.query(Category).filter_by(id=category_id, author_id=self.current_user, is_delete=0).first()
            if not category_obj:
                self.data_except("当前选择的分类不存在！")
            post_count = self.session.query(PostCateMiddle).filter_by(category_id=category_id).count()
            if post_count > 0:
                self.data_except("当前分类存在博文关联，无法删除！")
            category_obj.is_delete = 1
            self.session.commit()
            result["status"] = 1
            result["msg"] = "删除分类成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="删除分类成功！")
        self.write(result)


